package api

import (
	"github.com/gin-gonic/gin"
	"server/internal/app/model"
	"server/internal/app/serv"
	"server/internal/pkg/response"
	"strings"
)

var MenuApi = new(menuApi)

// MenuApi 菜单管理
type menuApi struct {
	model.MenuRule
}

// List 列表
func (a menuApi) List(c *gin.Context) {

	rules, _ := c.Get("rules")
	groupIds := strings.Split(rules.(string), ",")
	response.SuccessList(c, serv.Menu.List(0, rules, groupIds), 0)
}

// Detail 单条
func (a menuApi) Detail(c *gin.Context) {
	id := c.Query("id")

	_, detail := serv.Menu.Read(id)

	response.SuccessData(c, detail, "")
}

// Add 添加
func (a menuApi) Add(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Fail(c, err.Error(), "参数错误")
		return
	}

	if err := serv.Menu.Create(a.MenuRule); err.Error == nil {
		response.Success(c, "", "添加成功")
	} else {
		response.Fail(c, err, "添加失败")
	}
}

// Edit 编辑
func (a menuApi) Edit(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Fail(c, err.Error(), "参数错误")
		return
	}

	if serv.Menu.Update(a.MenuRule).Error == nil {
		response.Success(c, "", "编辑成功")
	} else {
		response.Fail(c, "", "编辑失败")
	}
}

// Del 删除
func (a menuApi) Del(c *gin.Context) {
	type Param struct {
		Ids []int `json:"ids"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Fail(c, err.Error(), "参数错误")
		return
	}
	if serv.Menu.Delete(param.Ids).Error == nil {
		response.Success(c, "", "删除成功")
	} else {
		response.Fail(c, "", "删除失败")
	}
}

// GetAsyncRoutes 获取权限下菜单
func (a menuApi) GetAsyncRoutes(c *gin.Context) {
	rules, _ := c.Get("rules")
	groupIds := strings.Split(rules.(string), ",")

	response.Success(c, serv.Menu.Tree(0, rules, groupIds), "")
}

// GetSelect 远程下啦
func (a menuApi) GetSelect(c *gin.Context) {
	rules, _ := c.Get("rules")
	groupIds := strings.Split(rules.(string), ",")

	response.Success(c, serv.Menu.Select(0, rules, groupIds), "")
}
